package com.spring.security.config;

import com.spring.security.authentication.MyAuthenticationFailHandler;
import com.spring.security.authentication.MyAuthenticationSuccessHandler;
import com.spring.security.properties.SecurityConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Title: BrowserSecurityConfig
 * Description:
 * Security 配置类，它里面会说明登录方式、登录页面、哪个url需要认证、注入登录失败/成功过滤器
 * @author yls
 * @created 2019/12/26 15:04
 */

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter{


    /**
     * 注入security属性类配置
     */
    @Autowired
    private SecurityConfigProperties securityProperties;

    /**
     * 注入 自定义的  登录成功处理类
     */
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;


    @Autowired
    private MyAuthenticationFailHandler  myAuthenticationFailHandler;



    /**
     * 重写PasswordEncoder  接口中的方法，实例化加密策略
     * @return
     */
    @Bean
    public PasswordEncoder  passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String redirectUrl = securityProperties.getBrowser().getLoginPage();
        //表单登录 方式
        http.formLogin()
                .loginPage("/authentication/require")
                //登录需要经过的url请求
                .loginProcessingUrl("/authentication/form")
                .successHandler(myAuthenticationSuccessHandler)
                .failureHandler(myAuthenticationFailHandler)
                .and()
                //请求授权
                .authorizeRequests()
                //不需要权限认证的url
                .antMatchers("/authentication/require",redirectUrl).permitAll()
                //任何请求
                .anyRequest()
                //需要身份认证
                .authenticated()
                .and()
                //关闭跨站请求防护
                .csrf().disable();
    }


}
